package com.mybatis.boost.mapper.autoconfigure;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.mapper.mapperhelper.MapperHelper;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.stream.Stream;

/**
 * @author jearton
 * @since 2017/2/6
 */
@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnBean({DataSource.class, SqlSessionFactory.class})
@AutoConfigureAfter(MybatisAutoConfiguration.class)
@EnableConfigurationProperties({MapperProperties.class})
public class MapperAutoConfiguration {

    private final SqlSessionFactory sqlSessionFactory;

    private final MapperProperties properties;

    public MapperAutoConfiguration(SqlSessionFactory sqlSessionFactory, MapperProperties properties) {
        this.sqlSessionFactory = sqlSessionFactory;
        this.properties = properties;
    }

    @PostConstruct
    public void replaceSqlSource() {
        MapperHelper mapperHelper = new MapperHelper();
        mapperHelper.setConfig(properties.toMapperConfig());
        Stream.of(properties.getMappers()).forEach(mapperHelper::registerMapper);
        mapperHelper.processConfiguration(sqlSessionFactory.getConfiguration());
    }
}
